package davidtps.godutch.database.base;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import davidtps.godutch.utility.Reflection;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteDBHelper extends SQLiteOpenHelper {

	private static SQLiteDBConfig SQLITE_DB_CONFIG;
	private static SQLiteDBHelper SQLITE_DB_HELPER;
	private Context mContext;
	
	
	public interface OnCreateTableListener{
		void onCreate(SQLiteDatabase db);
		void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
	}
	
	public static SQLiteOpenHelper getInstance(Context pContext){
		if(SQLITE_DB_HELPER==null){
			SQLITE_DB_CONFIG = SQLiteDBConfig.getInstance(pContext);
			SQLITE_DB_HELPER = new SQLiteDBHelper(pContext);
		}
		return SQLITE_DB_HELPER;
	}
	
	private SQLiteDBHelper(Context pContext){
		super(pContext, SQLITE_DB_CONFIG.getDatabasename(), null, SQLITE_DB_CONFIG.getDatabaseversion());
		mContext = pContext;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		ArrayList<String> _ArrayList = SQLITE_DB_CONFIG.getTables();
		Reflection _Reflection = new Reflection();
		for(int i=0;i<_ArrayList.size();i++){
			try {
				OnCreateTableListener _Listener = (OnCreateTableListener)_Reflection.newInstance(_ArrayList.get(i),new Object[]{mContext}, new Class[]{Context.class});
				_Listener.onCreate(db);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}
